import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Describe as : get various smallest width xml with victor.xml
 * Created by liaohailong on 2018/4/19.
 */
public class AutoDimenHelper {
    private static final String sResName = "res";
    private static final String sFileName = "victor.xml";

    // values-{height}x{width} in portrait
    private static final String sValuesName = "values-sw%sdp";
    private static final List<String> SUPPORT_DIMENSION = new ArrayList<>();

    static {
        // phone size and TV size
        // smallest width dp
        SUPPORT_DIMENSION.add("384");
        SUPPORT_DIMENSION.add("392");
        SUPPORT_DIMENSION.add("400");
        SUPPORT_DIMENSION.add("410");
        SUPPORT_DIMENSION.add("411");
        SUPPORT_DIMENSION.add("432");
        SUPPORT_DIMENSION.add("480");
        SUPPORT_DIMENSION.add("533");
        SUPPORT_DIMENSION.add("592");
        SUPPORT_DIMENSION.add("600");
        SUPPORT_DIMENSION.add("640");
        SUPPORT_DIMENSION.add("662");
        SUPPORT_DIMENSION.add("720");
        SUPPORT_DIMENSION.add("768");
        SUPPORT_DIMENSION.add("800");
        SUPPORT_DIMENSION.add("811");
        SUPPORT_DIMENSION.add("820");
        SUPPORT_DIMENSION.add("960");
        SUPPORT_DIMENSION.add("961");
        SUPPORT_DIMENSION.add("1024");
        SUPPORT_DIMENSION.add("1280");
        SUPPORT_DIMENSION.add("1365");
    }

    //this config is dependent on Mi-5s phone
    private static final int DEFAULT_WINDOW_WIDTH_DP = 360;
    private static final int DEFAULT_MAX_LENGTH_SIZE = 2340;
    private static final String DEFAULT_UNIT_PREFIX = "dp_";
    private static final String DEFAULT_UNIT_SUFFIX = "dp";



    public static void main(String[] args) {
        URL resource = AutoDimenHelper.class.getResource("");
        if (resource == null) {
            return;
        }
        System.out.println("-------------------------------- AutoDimenHelper start --------------------------------");
        File directoryFile = new File(resource.getPath());
        // 创建res目录
        String directoryPath = directoryFile.getAbsolutePath() + File.separator + sResName;
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            boolean mkdir = directory.mkdir();
            System.out.println("mkdir = " + mkdir + "  directory = " + directory.getAbsolutePath());
        }

        // 创建dimens文件
        String baseFilePath = directoryPath + File.separator + sFileName;
        generateBaseFile(baseFilePath);

        for (String sw : SUPPORT_DIMENSION) {
            generateValues(baseFilePath, directoryPath, sw);
        }
        System.out.println("-------------------------------- AutoDimenHelper end --------------------------------");
    }

    private static void generateBaseFile(String baseFilePath) {
        File file = new File(baseFilePath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            //get dimens
            StringBuilder sb = new StringBuilder();
            sb.append("<resources>").append("\n");
            //length size
            for (int i = 1; i <= DEFAULT_MAX_LENGTH_SIZE; i++) {
                sb.append("    <dimen name=\"")
                        .append(DEFAULT_UNIT_PREFIX)
                        .append(i)
                        .append("\">")
                        .append(i)
                        .append("dp")
                        .append("</dimen>")
                        .append("\n");
            }
            sb.append("</resources>");
            fos.write(sb.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(fos);
        }
    }

    private static void generateValues(String baseFilePath, String directoryPath, String smallestWidthDp) {
        int widthDp = Integer.parseInt(smallestWidthDp);

        File file = new File(baseFilePath);
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        String valuesFileName = String.format(sValuesName, widthDp);
        String valuesPath = directoryPath + File.separator + valuesFileName;
        File targetDirectory = new File(valuesPath);
        if (!targetDirectory.exists()) {
            boolean mkdir = targetDirectory.mkdir();
            System.out.println("mkdir = " + mkdir + "  directory = " + targetDirectory.getAbsolutePath());
        }

        String valueFilePath = valuesPath + File.separator + sFileName;
        File valueFile = new File(valueFilePath);
        FileOutputStream fos = null;

        try {
            reader = new FileReader(file);
            bufferedReader = new BufferedReader(reader);

            StringBuilder sb = new StringBuilder();
            sb.append("<resources>").append("\n");

            String tempLine;
            while ((tempLine = bufferedReader.readLine()) != null) {

                if (tempLine.contains("<dimen") && tempLine.contains("</dimen>")) {
                    generateDimSize(sb, tempLine, widthDp);
                }
            }

            sb.append("</resources>");

            fos = new FileOutputStream(valueFile);
            fos.write(sb.toString().getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            close(reader);
            close(bufferedReader);
            close(fos);
        }
    }

    private static void generateDimSize(StringBuilder sb, String tempLine, int width) {
        String unitPrefix = "\"" + DEFAULT_UNIT_PREFIX;
        int nameFrom = tempLine.lastIndexOf(unitPrefix);
        int nameTo = tempLine.lastIndexOf("\">");
        String valueName = tempLine.substring(nameFrom + unitPrefix.length(), nameTo);

        int from = tempLine.lastIndexOf("\">");
        int to = tempLine.lastIndexOf(DEFAULT_UNIT_SUFFIX);
        String value = tempLine.substring(from + "\">".length(), to);
        float valueFloat = Float.parseFloat(value);

        //transform value to correct screen...
        float scalePX = width * 1.0f / DEFAULT_WINDOW_WIDTH_DP;
        valueFloat *= scalePX;
        String valueStr = new BigDecimal(valueFloat).setScale(1, RoundingMode.HALF_UP).toString();

        sb.append("    <dimen name=")
                .append(unitPrefix)
                .append(valueName)
                .append("\">")
                .append(valueStr)
                .append(DEFAULT_UNIT_SUFFIX)
                .append("</dimen>")
                .append("\n");
    }


    private static void close(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}